/**
 * MenuItem
 * @authors 杨兴洲（of2502）
 * @date    2017/6/2 0002 11:50
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */
import React, {Component} from 'react';
import {findDOMNode} from 'react-dom';
import {DragSource, DropTarget} from 'react-dnd';
import MenuSubItem from "./MenuSubItem";
import GaUtil from "util/ga-util";


const cardSource = {
    beginDrag(props) {
        return {
            id: props.key,
            index: props.index,
        };
    },
};

const cardTarget = {
    hover(props, monitor, component) {
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
            return;
        }

        // Determine rectangle on screen
        const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();

        // Get vertical middle
        const hoverMiddleX = (hoverBoundingRect.left - hoverBoundingRect.right) / 2;

        // Determine mouse position
        const clientOffset = monitor.getClientOffset();

        // Get pixels to the top
        const hoverClientX = clientOffset.x - hoverBoundingRect.right;

        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%

        // Dragging downwards
        if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
            return;
        }

        // Dragging upwards
        if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
            return;
        }

        // Time to actually perform the action
        props.moveItem(dragIndex, hoverIndex);
        GaUtil.addEvent({eventAction: "菜单排序", eventLabel: "自定义菜单"})
        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        monitor.getItem().index = hoverIndex;
    },
};


@DropTarget("ITEM", cardTarget, connect => ({
    connectDropTarget: connect.dropTarget(),
}))
@DragSource("ITEM", cardSource, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
}))

// @DragDropContext(HTML5Backend)
export default class MenuItem extends Component {
    render() {

        const {selectedSubIndex, selectItem, selectSubItem, moveSubItem, isActive, index, data, subItems, addSubItem, connectDragSource, connectDropTarget} = this.props;
        const {name, type} = data;
        const btnAddSubItem = (
            <li onClick={(e) => {
                e.stopPropagation();
                addSubItem();
            }} className="menu-sub-button"><i className="qmIcon plus"></i></li>
        );
        return connectDragSource(connectDropTarget(
            <div key={index}
                 className={`menu-button ${isActive ? "active" : "" }`}
                 onClick={() => selectItem(index)}>
                {name}
                {subItems.size >= 0 &&
                <ul className="menu-sub-box"
                    style={{display: isActive ? "block" : "none"}}>
                    {
                        subItems.map((subItem, subIndex) => {
                            subItem = subItem.toObject();
                            return (
                                <MenuSubItem
                                    key={index + "-" + subIndex}
                                    index={subIndex}
                                    data={subItem}
                                    isActive={isActive && selectedSubIndex === subIndex}
                                    selectSubItem={() => selectSubItem(subIndex)}
                                    moveSubItem={moveSubItem}
                                />
                            )
                        })
                    }
                    {subItems.size < 5 && btnAddSubItem}
                </ul>
                }
            </div>
        ));
    }
}